<template>
  <Dialog ref="dialogRef" width="700px" :show-close="true">
    <div class="config-dialog">
      <div class="config-title">{{ t('game.config.configPage') }} <span class="config-sub">（{{ infoData.name }}）</span></div>
      <div class="config-table">
        <div class="config-row" v-for="(conf, key) in configData" :key="String(key)">
          <div class="config-label">{{ getFieldDisplayName(String(key)) }}</div>
          <div class="config-options">
            <label v-for="opt in getConfigOptions(conf)" :key="formatOpt(String(opt), String(key))" class="config-radio" :class="{active: getSelectedValue(configData[key]) === formatOpt(String(opt), String(key))}">
              <input 
                type="radio" 
                :value="formatOpt(String(opt), String(key))" 
                :checked="getSelectedValue(configData[key]) === formatOpt(String(opt), String(key))"
                @change="setSelectedValue(configData[key], formatOpt(String(opt), String(key)))" 
              />
              <span>{{ formatOpt(String(opt), String(key)) }}</span>
            </label>
          </div>
        </div>
      </div>
      <div class="config-btns">
        <button class="config-btn u-f-ajc primary" @click="onOk">{{ t('game.config.startTraining') }}</button>
        <button class="config-btn  u-f-ajc" @click="onCancel">{{ t('game.config.cancel') }}</button>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { defineExpose, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import Dialog from '../../../components/Dialog.vue'

// 翻译系统
const translationVersion = ref(0)
let t = (key: any, params?: any) => {
	const keys = key.split('.')
	let current: any = translations.value
	for (const k of keys) {
		if (current && typeof current === 'object') {
			current = current[k]
		} else {
			return key
		}
	}
	if (typeof current === 'string' && params) {
		return current.replace(/\{(\w+)\}/g, (match: any, key: any) => params[key] || match)
	}
	return current || key
}

const translations = ref<any>({})

async function initTranslations() {
	try {
		const currentLang = localStorage.getItem('language') || 'zh-CN'
		let langModule
		if (currentLang === 'en-US') {
			langModule = await import('../../../i18n/locales/en-US')
		} else {
			langModule = await import('../../../i18n/locales/zh-CN')
		}
		translations.value = langModule.default
		translationVersion.value++
	} catch (error) {
		console.error('Failed to load translations:', error)
	}
}

const emit = defineEmits(['onOk'])
const dialogRef = ref()
const router = useRouter()
let configData = reactive<any>({})
  // "trainingTime": "训练时长",
  // "trainingDifficulty": "训练难度", 
  // "imageType": "图片类型",
  // "neglectedSide": "忽略侧",
  // "trainingMode": "训练模式",
  // "mode": "模式",
  // "content": "内容",
  // "affectedHand": "患手",
  // "musicType": "音乐类型",
  // "type": "类型",
  // "recipe": "菜谱"
  // 字段名映射表
  let  fieldNameMap: any = {

}

// 获取字段显示名称
function getFieldDisplayName(fieldName: string) {
  const currentLang = localStorage.getItem('language') || 'zh-CN'
  
  // 如果是英文，直接返回原字段名
  if (currentLang === 'en-US') {
    return fieldName
  }
  
  // 如果是中文，使用映射表
  return fieldNameMap[fieldName] || fieldName
}

// 获取配置选项
function getConfigOptions(conf: any) {
  return conf.options || conf.选项 || []
}

// 获取选中状态（根据索引获取实际值）
function getSelectedValue(conf: any) {
  const options = getConfigOptions(conf)
  let selectedIndex = -1
  
  if (conf.hasOwnProperty('selected')) {
    selectedIndex = conf.selected
  } else if (conf.hasOwnProperty('选中')) {
    // 如果是旧格式的值，转换为索引
    const oldValue = conf.选中
    selectedIndex = options.findIndex((opt: any) => String(opt) === String(oldValue))
  }
  
  // 如果索引有效，返回对应的选项值
  if (selectedIndex >= 0 && selectedIndex < options.length) {
    return options[selectedIndex]
  }
  
  return options[0] || '' // 默认返回第一个选项
}

// 设置选中状态（设置索引）
function setSelectedValue(conf: any, value: any) {
  const options = getConfigOptions(conf)
  const index = options.findIndex((opt: any) => String(opt) === String(value))
  
  if (index >= 0) {
    conf.selected = index
  }
}

function formatOpt(opt: any, key: string) {
  // 针对"训练时间"字段，把数字转成"X 分钟"
  if (key.includes('时间') && typeof opt === 'number') {
    return opt + ' ' + t('game.config.minutes')
  }
  return String(opt)
}

let infoData = ref<any>({})
function show(item: any) { 
  console.log(item);
  fieldNameMap= JSON.parse(item.configField)
    infoData.value = item
  if (item && item.config) {
    const config = typeof item.config === 'string' ? JSON.parse(item.config) : item.config
    Object.keys(configData).forEach(k=>delete configData[k])
    Object.entries(config).forEach(([k,v])=>configData[k]=JSON.parse(JSON.stringify(v)))
  }
  dialogRef.value && dialogRef.value.open() 
}
function hide() { dialogRef.value && dialogRef.value.close() }
defineExpose({ show, hide })

function onOk() {
  // 打印选中的配置参数
  console.log('选中的配置参数：');
  let config:any={}
  config.task=JSON.parse(localStorage.getItem('taskId')||'{}')
  config.user = JSON.parse(localStorage.getItem('user') || '{}')
  config.config = configData
  config.language = localStorage.getItem('language')
  config.token = localStorage.getItem('token')

  config.game=infoData.value
  localStorage.setItem('selconfigData', JSON.stringify(config))
  
  for (const [key, config] of Object.entries(configData)) {
    // 详细调试信息
    const configItem = config as any;
    console.log(`配置项 "${key}" 的详细信息:`, configItem);
    console.log(`  - options: ${JSON.stringify(configItem.options)}`);
    console.log(`  - selected索引: ${configItem.selected}`);
    
    const selectedValue = getSelectedValue(configItem);
    console.log(`${key}: ${selectedValue} (索引: ${configItem.selected})`);
  }
  
  // 打印完整的配置对象
  console.log('完整配置对象：', configData);
  
  // 创建一个包含配置的对象传递给父组件
  const configResult: any = {};
  for (const [key, config] of Object.entries(configData)) {
    configResult[key] = getSelectedValue(config as any);
  }
  console.log('提取的配置结果：', configResult);
  
  // 打印游戏信息
  console.log('游戏信息：', infoData.value);
  
  // 将配置结果添加到游戏信息中
  const resultData = {
    ...infoData.value,
    selectedConfig: configResult
  };
  
  emit('onOk', resultData)
  hide()
  localStorage.setItem('webviewUrl',infoData.value.url)
  router.push({
    path: '/webView',
    query: {
      url: infoData.value.url+'?time='+new Date().getTime()
    }
  })
}
function onCancel() {
  hide()
}

onMounted(async () => {
	// 初始化翻译
	await initTranslations()
})
</script>

<style scoped>
.config-dialog {
  width: 1000px;
  margin: 0 auto;
  background: #fff;
  border-radius: 18px;
  padding: 38px 48px 38px 48px;
  display: flex;
  flex-direction: column;
  gap: 0;
}
.config-title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin-bottom: 18px;
}
.config-sub {
  font-size: 16px;
  color: #888;
  font-weight: normal;
}
.config-table {
  display: flex;
  flex-direction: column;
  gap: 0;
  margin-bottom: 18px;
}
.config-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding: 22px 0 25px 0;
}
.config-row:last-child {
  border-bottom: none;
}
.config-label {
  min-width: 120px;
  width: auto;
  font-size: 20px;
  color: #333;
  font-weight: 500;
  text-align: left;
  padding-left: 18px;
  padding-right: 20px;
  flex-shrink: 0;
  white-space: nowrap;
}
.config-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 32px 32px;
  align-items: center;
}
.config-radio {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #999 !important;
  cursor: pointer;
  position: relative;
  user-select: none;
}
.config-radio input[type="radio"] {
  appearance: none;
  width: 22px;
  height: 22px;
  border: 2px solid #b5d2e8;
  border-radius: 50%;
  margin-right: 8px;
  outline: none;
  background: #fff;
  transition: border 0.2s;
}
.config-radio.active input[type="radio"] {
  border: 7px solid #2176b8;
}
.config-radio.active span {
  color: #2176b8;
  font-weight: bold;
}
.config-radio span {
  color: #999;
  font-size: 18px;
}
.config-btns {
  display: flex;
  justify-content: center;
  gap: 32px;
  margin-top: 38px;
}
.config-btn {
  min-width: 180px;
  height: 48px;
  border-radius: 24px;
  font-size: 22px;
  font-weight: 500;
  border: 1px solid #d3d3d5 !important;
  border: none;
  outline: none;
  cursor: pointer;
  color: #999;
  transition: background 0.2s, color 0.2s;
}
.config-btn.primary {
  background: var(--theme-primary);
  color: #fff;
}
.config-btn.primary:hover {
  background: #2176b8;
}
.config-btn:hover:not(.primary) {
  background: #eaf4fa;
}
</style>
